import router from "./router";
import { usePermissionStore } from "./store/permisson";
import { useUserStore } from "./store/user";
import { getToken } from "./utils/auth";

const whiteList = ["/login"];
router.beforeEach(async (to, from) => {
    const userStore = useUserStore();
    const permissionStore = usePermissionStore();
    const { getInfo, setRequestMenuNum } = useUserStore();
    setRequestMenuNum();
    userStore.user.menus = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const hasMenus = userStore.user.menus?.length > 0;
    const requestMenusNum = userStore.user?.requestMenuNum;
    // const hasToken = getToken();
    const hasToken = true;
    if (hasToken) {
        // if is logged in, redirect to the home page
        if (to.path === "/login") {
            if (hasMenus) {
                return { path: "/" };
            }
            return true;
        } else {
            if (hasMenus && requestMenusNum > 1) {
                return true;
            } else {
                try {
                    const userInfo = await getInfo();
                    // const menus = userInfo.permissionList;
                    const menus = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                    const permissionKey = to.meta.permissionKey;
                    if (permissionKey && !menus?.includes(permissionKey as number)) {
                        return "/403";
                    }

                    const accessRoutes = permissionStore.generateRoutes(menus);
                    // dynamically add accessible routes
                    accessRoutes.forEach((route) => {
                        router.addRoute(route);
                    });
                    // setRequestMenuNum();
                    return to.fullPath;
                } catch (error) {
                    // remove token and go to login page to re-login
                    userStore.resetToken();
                    return `/login?redirect=${to.fullPath}`;
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            return true;
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            return `/login?redirect=${to.fullPath}`;
        }
    }
});
